package com.zhouhailin;

import java.util.Optional;

/**
 * 获取值
 *
 * @Author zhouhailin
 * @date 2023/1/19 10:36
 */
public class GetOptionalDemo {
    public static void main(String[] args) {
        String name = null;
        Optional<String> optOrNull = Optional.ofNullable(name);
        System.out.println(optOrNull.get());

        // 运行上面程序会抛出如下异常：
        /**
         * Exception in thread "main" java.util.NoSuchElementException: No value present
         * 	at java.util.Optional.get(Optional.java:135)
         * 	at com.zhouhailin.GetOptionalDemo.main(GetOptionalDemo.java:15)
         */

        // 建议使用orElseGet()方法获取 Optional对象的值，下面输出值：zhouhailin
        System.out.println(optOrNull.orElseGet(() -> "zhouhailin"));
    }
}
